class Character < ActiveRecord::Base
  validates_format_of :name, :with => /[A-Z][a-z]+/
  validates_uniqueness_of :name
  belongs_to :character_class
  belongs_to :user
  has_many :characters_role
  has_many :characters_reward, :dependent => :destroy
  has_many :rewards, :through => :characters_reward
  has_many :roles, :through => :characters_role
  has_many :loot, :dependent => :destroy
  has_many :items, :through => :loot

  @dkp_earned = nil

  # always put inactive characters last
  def <=>(other)
    if (self.active? == true and other.active? == false)
      -1
    elsif (self.active? == false and other.active? == true)
      1
    else
      self.name <=> other.name
    end
  end

  def raids
    all_raids = []
    self.rewards.each { |r| all_raids << r.raid }
    all_raids.uniq.sort { |a,b| b.date <=> a.date }
  end

  def number_of_shares
    sum = 0
    n = self.rewards.sum(:number_of_shares)
    sum += n unless n.nil?
    return sum
  end

  def dkp_spent
    sum = 0.0
    n = self.loot.sum(:price)
    sum += n unless n.nil?
    return sum
  end

  def dkp_earned
    if @dkp_earned == nil
      share_value = 0.0
      if Reward.total_number_of_shares != 0
        share_value = (Loot.total_value / Reward.total_number_of_shares)
      end
      @dkp_earned = number_of_shares * share_value
    end

    return @dkp_earned
  end

  def dkp
    dkp_earned - dkp_spent
  end

  def inactive?
    active? == false
  end

end
